package com.itboye.shop;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.itboye.shop.adapter.OldShopCarAdapter;
import com.itboye.shop.app.MyApplication;
import com.itboye.shop.base.BaseFragment;
import com.itboye.shop.bean.ShopCarBean;
import com.itboye.shop.category.store.GoodDetailActivity;
import com.itboye.shop.category.store.QueRenDingDanNew;
import com.itboye.shop.common.swipexpandlistview.BaseSwipeMenuExpandableListAdapter;
import com.itboye.shop.common.swipexpandlistview.ContentViewWrapper;
import com.itboye.shop.common.swipexpandlistview.ShopcartExpandableListViewAdapter;
import com.itboye.shop.common.swipexpandlistview.SwipeMenu;
import com.itboye.shop.common.swipexpandlistview.SwipeMenuExpandableCreator;
import com.itboye.shop.common.swipexpandlistview.SwipeMenuExpandableListView;
import com.itboye.shop.common.swipexpandlistview.SwipeMenuItem;
import com.itboye.shop.me.LoginActivity;
import com.itboye.shop.net.ResultEntity;
import com.itboye.shop.presenter.ShopPresenter;
import com.itboye.shop.util.helper.ImageLoader;
import com.itboye.shop.util.helper.utils.MyListView;
import com.itboye.shop.util.helper.utils.XScrollView;
import com.itboye.shop.util.loadutil.Const;
import com.itboye.shop.util.loadutil.IsUtilUid;
import com.itboye.shop.util.loadutil.MAlert;
import com.itboye.shop.util.loadutil.SPUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 购物车
 */
public class FragmentShopcart extends BaseFragment implements ShopcartExpandableListViewAdapter.CheckInterface,
        ShopcartExpandableListViewAdapter.ModifyCountInterface, OnClickListener, Observer {
    private SwipeMenuExpandableListView exListView;
    // private CheckBox cb_check_all;
    private TextView tv_total_price;
    private TextView tv_delete;
    private TextView tv_go_to_pay;
    private Context context;
    //    private ShopCarBeanCopy shopCarBean;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    TextView txt_title;
    private ShopcartExpandableListViewAdapter selva;
    // private List<GroupInfo> groups = new ArrayList<GroupInfo>();// 组元素数据列表
    protected String uid = "";
    ShopPresenter carPresenter;
    LinearLayout bottom;
    //	RefreshLayout refresh;
    public static String changeCart = "changeshopcart";
    TextView guang;
    ArrayList<ShopCarBean> shopCarBean;
    ArrayList<ShopCarBean.GoodsEntity> oldCarBean;
    ArrayList<ShopCarBean> bean;
    TextView tvTest, tvTitle;
    boolean isEdit = false;
    ImageView back;

    XScrollView my_scview;

    private String[] bigstrs = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"};
    private ArrayAdapter<String> bigAdapter;
    MyListView gouwu_listView;
    OldShopCarAdapter oldAdapter;
    private Dialog dialog;// 自定义Dialog
    ShopCarBean model;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_shopcart, null);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uid = (String) SPUtils.get(getContext(), null, Const.ID, "");
        tvTest.setText("编辑");
        tvTitle.setText("购物车");
        tvTest.setVisibility(View.VISIBLE);
        back.setVisibility(View.GONE);
        bigAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, bigstrs);
        showExtraDialog();
        if (uid == "" || uid == null) {
            setInvisible();
        } else {
            setVisible();
        }
        carPresenter = new ShopPresenter(this);
        if (uid == "" || uid == null) {

        } else {
            carPresenter.gouWuChe(IsUtilUid.sId(), uid);
        }
        exListView.setMenuCreator(creator);
        exListView
                .setOnMenuItemClickListener(new SwipeMenuExpandableListView.OnMenuItemClickListenerForExpandable() {

                    @Override
                    public boolean onMenuItemClick(int groupPosition,
                                                   int childPosition, SwipeMenu menu, int index) {
                        // TODO Auto-generated method stub
                        // ByAlert.alert("groupPosition" + groupPosition
                        // + "childPosition" + childPosition);
                        ShopCarBean model = new ShopCarBean();
                        model.setUid(uid);
                        model.setId(shopCarBean.get(groupPosition)
                                .getGoods().get(childPosition).getId());
                        carPresenter.deleteShop(model);
                        return true;
                    }
                });
        exListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(),
                        GoodDetailActivity.class);
                intent.putExtra("goodsId",
                        shopCarBean.get(groupPosition).getGoods()
                                .get(childPosition).getP_id());
                intent.putExtra("goodsName",
                        shopCarBean.get(groupPosition).getGoods()
                                .get(childPosition).getName());
                startActivity(intent);
                return true;
            }
        });
        //长按
        gouwu_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                model = new ShopCarBean();
                model.setUid(uid);
                model.setId(shopCarBean.get(groupPosition)
                        .getGoods().get(childPosition).getId());
                dialog.show();
                return true;
            }
        });
        IntentFilter filter = new IntentFilter(changeCart);
        getActivity().registerReceiver(broadcastReceiver, filter);
    }

//	@Override
//	public void onMyActivityCreated() {
//		// TODO Auto-generated method stub
//		mAppList = getActivity().getPackageManager()
//				.getInstalledApplications(0);


//		IntentFilter filter = new IntentFilter(changeCart);
//		getActivity().registerReceiver(broadcastReceiver, filter);
//		carPresenter = new ShopCarPresenter(this);
//		if (uid == "" || uid == null) {
//
//		} else
//			carPresenter.getShopcar(uid);
//		initView2();
//		back.setVisibility(View.GONE);
//		txt_title.setVisibility(View.VISIBLE);
//		txt_title.setText("购物车");
    // 加载监听器
    // refresh.setRefreshing(true);
    // refresh.set
    // refresh.setLoading(true);
//		refresh.setOnLoadListener(new OnLoadListener() {
//
//			@Override
//			public void onLoad() {
//
//				Toast.makeText(getActivity(), "load", Toast.LENGTH_SHORT)
//						.show();
//
//				refresh.postDelayed(new Runnable() {
//
//					@Override
//					public void run() {
//						// 加载完后调用该方法
//						refresh.setLoading(false);
//					}
//				}, 1500);
//
//			}
//		});
//		refresh.setOnRefreshListener(new OnRefreshListener() {
//
//			@Override
//			public void onRefresh() {
//				// TODO Auto-generated method stub
//				refresh.postDelayed(new Runnable() {
//
//					@Override
//					public void run() {
//						// 加载完后调用该方法
//						refresh.setRefreshing(false);
//					}
//				}, 1500);
//			}
//		});
//		exListView.setMenuCreator(creator);

//		guang.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				Intent intent = new Intent("set");
//				intent.putExtra("index", 0);
//				getActivity().sendBroadcast(intent);
//			}
//		});

//	}

    /**
     * 购物车为空
     */
    public void setInvisible() {
        if (uid.equals("")) {
            getView().findViewById(R.id.btn_login).setVisibility(View.VISIBLE);
            getView().findViewById(R.id.btn_login).setOnClickListener(
                    new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            startActivity(new Intent(getActivity(),
                                    LoginActivity.class));
                        }
                    });
            getView().findViewById(R.id.btn_login).setVisibility(View.VISIBLE);
            getView().findViewById(R.id.totop).setVisibility(View.GONE);
        } else {
            getView().findViewById(R.id.totop).setVisibility(View.VISIBLE);
            getView().findViewById(R.id.btn_login).setVisibility(View.GONE);
        }
        //   exListView.setVisibility(View.GONE);
        my_scview.setVisibility(View.GONE);
        getView().findViewById(R.id.bottom).setVisibility(View.GONE);
        tvTest.setVisibility(View.GONE);
    }

    public void setVisible() {
        getView().findViewById(R.id.btn_login).setVisibility(View.GONE);
        // getView().findViewById(R.id.delete).setVisibility(View.VISIBLE);
        // getView().findViewById(R.id.selectedAll).setVisibility(View.VISIBLE);
        //  exListView.setVisibility(View.VISIBLE);
        my_scview.setVisibility(View.VISIBLE);
        getView().findViewById(R.id.bottom).setVisibility(View.VISIBLE);
        tvTest.setVisibility(View.VISIBLE);
    }

    SwipeMenuExpandableCreator creator = new SwipeMenuExpandableCreator() {
        @Override
        public void createGroup(SwipeMenu menu) {
            // Create different menus depending on the view type
//            SwipeMenuItem item2 = new SwipeMenuItem(getActivity());
//            item2.setBackground(new ColorDrawable(Color.rgb(0xFF, 0x6E, 0xA5)));
//            item2.setWidth(dp2px(90));
//            item2.setTitle("删除");
//            item2.setTitleColor(R.color.white);
//            // item2.setIcon(R.drawable.ic_action_discard);
//            menu.addMenuItem(item2);
            // switch (menu.getViewType()) {
            // case 0:
            // createMenu1(menu);
            // break;
            // case 1:
            // createMenu2(menu);
            // break;
            // case 2:
            // createMenu3(menu);
            // break;
            // }
        }

        @Override
        public void createChild(SwipeMenu menu) {
            // Create different menus depending on the view type
            SwipeMenuItem item2 = new SwipeMenuItem(getActivity());
//            item2.setBackground(new ColorDrawable(Color.rgb(0xff, 0x6e, 0xa5)));
            item2.setBackground(R.color.orange);
            item2.setWidth(dp2px(90));
            item2.setTitle("删除");
            item2.setTitleSize(18);
            item2.setTitleColor(Color.parseColor("#ffffff"));
            // item2.setIcon(R.drawable.ic_action_discard);
            menu.addMenuItem(item2);
        }
    };

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        //
        @Override
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(getContext(), null, Const.ID,
                    "");
            MAlert.alert("刷新中");
            if (!uid.equals("") && uid != null) {
                carPresenter.gouWuChe(IsUtilUid.sId(), uid);
                setVisible();
            } else {
                setInvisible();
            }
        }
    };
    private AppAdapter mAdapter;

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private void initView2() {
        context = getActivity();
        // virtualData();
        exListView = (SwipeMenuExpandableListView) getActivity().findViewById(
                R.id.exListView);
        // cb_check_all = (CheckBox)
        // getActivity().findViewById(R.id.all_chekbox);
        tv_total_price = (TextView) getActivity().findViewById(
                R.id.tv_total_price);
        tv_delete = (TextView) getActivity().findViewById(R.id.tv_delete);
        tv_go_to_pay = (TextView) getActivity().findViewById(R.id.tv_go_to_pay);
    }

    @SuppressWarnings("deprecation")
    private void initEvents() {
        mAdapter = new AppAdapter();
        exListView.setAdapter(mAdapter);
        oldAdapter = new OldShopCarAdapter(getActivity(), oldCarBean);
        gouwu_listView.setAdapter(oldAdapter);
        mAdapter.setCheckInterface(this);// 关键步骤1,设置复选框接口
        mAdapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        for (int i = 0; i < mAdapter.getGroupCount(); i++) {
            exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
        }
        calculate();
    }

    /**
     * adapter
     */
    class AppAdapter extends BaseSwipeMenuExpandableListAdapter {
        ShopcartExpandableListViewAdapter.CheckInterface checkInterface;
        ShopcartExpandableListViewAdapter.ModifyCountInterface modifyCountInterface;
        ViewHolder holder = null;

        /**
         * Whether this group item swipable
         *
         * @return
         */
        public void setCheckInterface(ShopcartExpandableListViewAdapter.CheckInterface checkInterface) {
            this.checkInterface = checkInterface;
        }

        public void setModifyCountInterface(
                ShopcartExpandableListViewAdapter.ModifyCountInterface modifyCountInterface) {
            this.modifyCountInterface = modifyCountInterface;
        }

        @Override
        public boolean isGroupSwipable(int groupPosition) {
            return true;
        }

        /**
         * Whether this child item swipable
         *
         * @param groupPosition
         * @param childPosition
         * @return
         */
        @Override
        public boolean isChildSwipable(int groupPosition, int childPosition) {
            return true;
        }

        @Override
        public int getChildType(int groupPosition, int childPosition) {
            return childPosition % 3;
        }

        @Override
        public int getChildTypeCount() {
            return 3;
        }

        @Override
        public int getGroupType(int groupPosition) {
            return groupPosition % 3;
        }

        @Override
        public int getGroupTypeCount() {
            return 3;
        }

        class ViewHolder {
            SimpleDraweeView iv_icon;
            TextView tv_name, tv_guige, tv_intro, tv_price, tv_type_size, tv_num,
                    tv_reduce, tv_add, tv_count, tv_newprice, tv_oldprice, tv_num2;
            CheckBox cb_check, determine_chekbox;
            Button btn_delete;
            RelativeLayout delete_view, undelete_view;

            public ViewHolder(View view) {
                // iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
                tv_name = (TextView) view.findViewById(R.id.tv_source_name);
                determine_chekbox = (CheckBox) view
                        .findViewById(R.id.determine_chekbox);
                view.setTag(this);
            }

            public ViewHolder(View view, int type) {
                iv_icon = (SimpleDraweeView) view
                        .findViewById(R.id.iv_adapter_list_pic);
                tv_name = (TextView) view.findViewById(R.id.tv_intro);
                tv_guige = (TextView) view.findViewById(R.id.tv_guige);
                tv_intro = (TextView) view.findViewById(R.id.tv_intro);
                tv_price = (TextView) view.findViewById(R.id.tv_price);
                tv_type_size = (TextView) view.findViewById(R.id.tv_type_size);
                tv_num = (TextView) view.findViewById(R.id.tv_num);
                cb_check = (CheckBox) view.findViewById(R.id.check_box);
                tv_reduce = (TextView) view.findViewById(R.id.tv_reduce);
                tv_add = (TextView) view.findViewById(R.id.tv_add);
                tv_count = (TextView) view.findViewById(R.id.tv_num);
                btn_delete = (Button) view.findViewById(R.id.btn_delete);
                delete_view = (RelativeLayout) view.findViewById(R.id.delete_view);
                undelete_view = (RelativeLayout) view.findViewById(R.id.undelete_view);
                tv_newprice = (TextView) view.findViewById(R.id.tv_newprice);
                tv_oldprice = (TextView) view.findViewById(R.id.tv_oldprice);
                tv_num2 = (TextView) view.findViewById(R.id.tv_num2);
                view.setTag(this);
            }
        }

        @Override
        public int getGroupCount() {
            return shopCarBean.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return shopCarBean.get(groupPosition).getGoods().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return shopCarBean.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            ShopCarBean.GoodsEntity childs = shopCarBean.get(groupPosition).getGoods()
                    .get(childPosition);
            return childs;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public ContentViewWrapper getGroupViewAndReUsable(
                final int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {
            boolean reUseable = true;
            if (convertView == null) {
                convertView = LayoutInflater.from(MyApplication.instatnce).inflate(R.layout.item_shopcart_group, null);
                convertView.setTag(new ViewHolder(convertView));
                reUseable = false;
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            holder.tv_name.setText(shopCarBean.get(groupPosition).getStore_name());
            holder.determine_chekbox.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v)

                {
                    shopCarBean.get(groupPosition)
                            .setSelected(((CheckBox) v).isChecked());
                    checkInterface.checkGroup(groupPosition,
                            ((CheckBox) v).isChecked());// 暴露组选接口
                }
            });
            holder.determine_chekbox.setChecked(shopCarBean
                    .get(groupPosition).isSelected());
            return new ContentViewWrapper(convertView, reUseable);
        }

        @Override
        public ContentViewWrapper getChildViewAndReUsable(
                final int groupPosition, final int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {
            boolean reUseable = true;
            if (convertView == null) {
                convertView = LayoutInflater.from(MyApplication.instatnce).inflate(R.layout.item_shopcart_product, null);
                convertView.setTag(new ViewHolder(convertView, 0));
                reUseable = false;
            }
            holder = (ViewHolder) convertView.getTag();
            if (null == holder) {
                holder = new ViewHolder(convertView, 0);
            }

            convertView.setBackgroundColor(Color.GRAY);
            ImageLoader.loadImage(holder.iv_icon, Const.IMAGE_HEAD
                    + shopCarBean.get(groupPosition).getGoods()
                    .get(childPosition).getIcon_url());
            holder.tv_name.setText(shopCarBean.get(groupPosition)
                    .getGoods().get(childPosition).getName());
            holder.tv_guige.setText(shopCarBean.get(groupPosition)
                    .getGoods().get(childPosition).getSku_desc());
            holder.tv_price.setText("￥"
                    + Double.parseDouble(shopCarBean.get(groupPosition).getGoods()
                    .get(childPosition).getPrice()) / 100 + "");

            holder.tv_num.setText(shopCarBean.get(groupPosition)
                    .getGoods().get(childPosition).getCount()
                    + "");
            holder.cb_check.setChecked(shopCarBean
                    .get(groupPosition).getGoods().get(childPosition)
                    .isSelected());
            holder.delete_view.setVisibility(shopCarBean.get(groupPosition).getGoods()
                    .get(childPosition).isDelete() ? View.VISIBLE : View.GONE);
            holder.btn_delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    ShopCarBean shopCarBeanInner = new ShopCarBean();
                    shopCarBeanInner.setUid(uid);
                    shopCarBeanInner.setId(shopCarBean.get(groupPosition).getGoods().get(childPosition).getId());
                    carPresenter.deleteShop(shopCarBeanInner);
                }
            });
            holder.tv_num2.setText("x" + shopCarBean.get(groupPosition).getGoods().get(childPosition).getCount());
            holder.tv_newprice.setText("￥" + Double.parseDouble(shopCarBean.get(groupPosition).getGoods().get(childPosition).getPrice()) / 100);
            holder.tv_oldprice.setText("￥" + Double.parseDouble(shopCarBean.get(groupPosition).getGoods().get(childPosition).getPrice()) / 100);
            holder.tv_oldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线

            holder.tv_oldprice.setVisibility(View.GONE);
            holder.cb_check.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    shopCarBean.get(groupPosition).getGoods()
                            .get(childPosition)
                            .setSelected(((CheckBox) v).isChecked());
                    holder.cb_check.setChecked(((CheckBox) v).isChecked());
                    checkInterface.checkChild(groupPosition, childPosition,
                            ((CheckBox) v).isChecked());// 暴露子选接口
                }
            });
            holder.tv_add.setTag(shopCarBean.get(groupPosition)
                    .getGoods().get(childPosition).getId());
            holder.tv_add.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    modifyCountInterface.doIncrease(groupPosition,
                            childPosition, holder.tv_count,
                            holder.cb_check.isChecked(), v.getTag() + "");// 暴露增加接口
                }
            });
            holder.tv_reduce.setTag(shopCarBean.get(groupPosition)
                    .getGoods().get(childPosition).getId());
            holder.tv_reduce.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    modifyCountInterface.doDecrease(groupPosition,
                            childPosition, holder.tv_count,
                            holder.cb_check.isChecked(), v.getTag() + "");// 暴露删减接口
                }
            });
            // holder.tv_name.setText("this is child");
            return new ContentViewWrapper(convertView, reUseable);
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

    /**
     * 模拟数据<br>
     * 遵循适配器的数据列表填充原则，组元素被放在一个List中，对应的组元素下辖的子元素被放在Map中，<br>
     * 其键是组元素的Id(通常是一个唯一指定组元素身份的值)
     */
    // private void virtualData()
    // {
    //
    // for (int i = 0; i < shopCarBean.size(); i++)
    // {
    //
    // groups.add(new GroupInfo(i + "", "第八号当铺" + (i + 1) + "号店"));
    //
    // List<ProductInfo> products = new ArrayList<ProductInfo>();
    // for (int j = 0; j <= i; j++)
    // {
    //
    // products.add(new ProductInfo(j + "", "商品", "", groups.get(i).getName() +
    // "的第" + (j + 1) + "个商品", 120.00 + i * j, 1));
    // }
    // children.put(groups.get(i).getId(), products);//
    // 将组元素的一个唯一值，这里取Id，作为子元素List的Key
    // }
    // }

    ArrayList<String> idsArray = new ArrayList<>();

    @Override
    public void onClick(View v) {
        AlertDialog alert;
        switch (v.getId()) {
            // case R.id.all_chekbox:
            // doCheckAll();
            // break;
            case R.id.guang:
                MainActivity.onSetFragment().setTabSelection(1);
                break;
            case R.id.tv_go_to_pay:
                if (totalCount == 0) {
                    MAlert.alert("请选择要支付的商品");
                    return;
                }
                alert = new AlertDialog.Builder(getActivity()).create();
                alert.setTitle("操作提示");
                alert.setMessage("总计:\n" + totalCount + "种商品\n"
                        + totalPrice + "元");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ArrayList<ShopCarBean> arrayGroup = new ArrayList<ShopCarBean>();
                                for (int i = 0; i < shopCarBean.size(); i++) {
                                    if (shopCarBean.get(i).isSelected()) {
                                        arrayGroup.add(shopCarBean.get(
                                                i));
                                    } else {
                                        for (int j = 0; j < shopCarBean
                                                .get(i).getGoods().size(); j++) {
                                            if (shopCarBean.get(i)
                                                    .getGoods().get(j).isSelected()) {
                                                arrayGroup.add(shopCarBean
                                                        .get(i));
                                                j = shopCarBean.get(i)
                                                        .getGoods().size();
                                            }
                                        }
                                    }
                                }
                                Intent intent = new Intent(getActivity(),
                                        QueRenDingDanNew.class);
                                intent.putExtra("price", totalPrice + "");
                                intent.putExtra("list", arrayGroup);
                                startActivity(intent);
                                return;
                            }
                        });
                alert.show();
                break;
            case R.id.tv_delete:
                if (totalCount == 0) {
                    MAlert.alert("请选择要移除的商品");
                    return;
                }
                alert = new AlertDialog.Builder(getActivity()).create();
                alert.setTitle("操作提示");
                alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doDelete();
                            }
                        });
                alert.show();
                break;
            case R.id.tvTest:
                if (isEdit) {
                    tvTest.setText("完成");
                } else {
                    tvTest.setText("编辑");
                }
                if (shopCarBean != null) {
                    for (ShopCarBean carBean : shopCarBean) {
                        if (isEdit) {
                            carBean.setDelete(false);
                            carBean.setSelected(false);
                        } else {
                            carBean.setDelete(true);
                            carBean.setSelected(true);
                        }
                        for (ShopCarBean.GoodsEntity goodsEntity : carBean.getGoods()) {
                            if (isEdit) {
                                goodsEntity.setDelete(false);
                                goodsEntity.setSelected(false);
                            } else {
                                goodsEntity.setDelete(true);
                                goodsEntity.setSelected(true);
                            }
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }
                isEdit = !isEdit;
                break;
        }
    }

    /**
     * 删除操作<br>
     * 1.不要边遍历边删除，容易出现数组越界的情况<br>
     * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
     */
    StringBuffer ids = new StringBuffer();
    private int currentCountTemp;
    private int groupPosition;
    private int childPosition;
    private String id;

    protected void doDelete() {
        if (ids.length() > 0) {

        }
        List<ShopCarBean> toBeDeleteGroups = new ArrayList<>();//
        // 待删除的组元素列表
        for (int i = 0; i < shopCarBean.size(); i++) {
            ShopCarBean group = shopCarBean.get(i);
            if (group.isSelected()) {
                toBeDeleteGroups.add(group);
            }
            List<ShopCarBean.GoodsEntity> toBeDeleteProducts = new ArrayList<>();// 待删除的子元素列表
            for (int j = 0; j < shopCarBean.get(i).getGoods()
                    .size(); j++) {
                if (shopCarBean.get(i).getGoods().get(j)
                        .isSelected()) {
                    toBeDeleteProducts.add(shopCarBean.get(i)
                            .getGoods().get(j));
                    ids.append(shopCarBean.get(i).getGoods().get(j)
                            .getId()
                            + ",");
                }
            }
            // shopCarBean.get(i).getGoods().removeAll(toBeDeleteProducts);//删除商品

        }
        //
        // shopCarBean.removeAll(toBeDeleteGroups);// 删除组元素
        ShopCarBean model = new ShopCarBean();
        model.setUid(uid);
        model.setId(ids.substring(0, ids.length() - 1));
        carPresenter.deleteShop(model);
    }

    @Override
    public void doIncrease(int groupPosition, int childPosition,
                           View showCountView, boolean isChecked, String id) {
        ShopCarBean.GoodsEntity product = (ShopCarBean.GoodsEntity) mAdapter
                .getChild(groupPosition, childPosition);
        int currentCount = Integer.parseInt(product.getCount());
        currentCount++;
        currentCountTemp = currentCount;

        this.groupPosition = groupPosition;
        this.childPosition = childPosition;
        this.id = shopCarBean.get(groupPosition).getGoods()
                .get(childPosition).getId();
        ShopCarBean model = new ShopCarBean();
        model.setUid(uid);
        model.setId(shopCarBean.get(groupPosition).getGoods()
                .get(childPosition).getId());
        model.setCount(currentCount + "");
        carPresenter.updateShop(model);
    }

    @Override
    public void doDecrease(int groupPosition, int childPosition,
                           View showCountView, boolean isChecked, String id) {
        ShopCarBean.GoodsEntity product = (ShopCarBean.GoodsEntity) mAdapter
                .getChild(groupPosition, childPosition);
        int currentCount = Integer.parseInt(product.getCount());
        if (currentCount == 1) {
            MAlert.alert("不能再减啦!");
            return;
        }
        currentCount--;
        currentCountTemp = currentCount;
        this.groupPosition = groupPosition;
        this.childPosition = childPosition;
        this.id = shopCarBean.get(groupPosition).getGoods()
                .get(childPosition).getId();
        ShopCarBean model = new ShopCarBean();
        model.setUid(uid);
        model.setId(shopCarBean.get(groupPosition).getGoods()
                .get(childPosition).getId());
        model.setCount(currentCount + "");
        carPresenter.updateShop(model);
    }

    @Override
    public void checkGroup(int groupPosition, boolean isChecked) {
        ShopCarBean group = shopCarBean.get(
                groupPosition);
        for (int i = 0; i < group.getGoods().size(); i++) {
            group.getGoods().get(i).setSelected(isChecked);
        }
        // if (isAllCheck())
        // cb_check_all.setChecked(true);
        // else
        // cb_check_all.setChecked(false);
        mAdapter.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void checkChild(int groupPosition, int childPosiTion,
                           boolean isChecked) {
        boolean allChildSameState = true;// 判断改组下面的所有子元素是否是同一种状态
        ShopCarBean group = shopCarBean.get(
                groupPosition);
        for (int i = 0; i < group.getGoods().size(); i++) {
            if (group.getGoods().get(i).isSelected() != isChecked) {
                allChildSameState = false;
                break;
            }
        }
        if (allChildSameState) {
            group.setSelected(isChecked);// 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
        } else {
            group.setSelected(false);// 否则，组元素一律设置为未选中状态
        }

        // if (isAllCheck())
        // cb_check_all.setChecked(true);
        // else
        // cb_check_all.setChecked(false);
        mAdapter.notifyDataSetChanged();
        calculate();
    }

    private boolean isAllCheck() {

        for (ShopCarBean group : shopCarBean) {
            if (!group.isSelected())
                return false;

        }

        return true;
    }

    // /** 全选与反选 */
    // private void doCheckAll() {
    // for (int i = 0; i < shopCarBean.getData().size(); i++) {
    // shopCarBean.getData().get(i)
    // .setSelected(cb_check_all.isChecked());
    // ShopCarBeanCopy.StoreList group = shopCarBean.getData().get(i);
    // for (int j = 0; j < group.getGoods().size(); j++) {
    // group.getGoods().get(j).setSelected(cb_check_all.isChecked());
    // }
    // }
    // mAdapter.notifyDataSetChanged();
    // }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < shopCarBean.size(); i++) {
            for (int j = 0; j < shopCarBean.get(i).getGoods()
                    .size(); j++) {
                ShopCarBean.GoodsEntity product = shopCarBean
                        .get(i).getGoods().get(j);
                if (product.isSelected()) {
                    totalCount++;
                    totalPrice += Float.parseFloat(product.getPrice())
                            * Integer.parseInt(product.getCount());
                }
            }
        }
        tv_total_price.setText("￥" + totalPrice);
        tv_go_to_pay.setText("去支付(" + totalCount + ")");
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity.getEventType() == ShopPresenter.query_carsuccess) {
            bean = (ArrayList<ShopCarBean>) entity.getData();
            shopCarBean = new ArrayList<ShopCarBean>();
            oldCarBean = new ArrayList<ShopCarBean.GoodsEntity>();
            for (int i = 0; i < bean.size(); i++) {
                for (int j = 0; j < bean.get(i).getGoods().size(); j++) {
                    if (bean.get(i).getGoods().get(j).getItem_status().equals("1")) {
                        shopCarBean.removeAll(bean);
                        shopCarBean.addAll(bean);
                    } else {
                        oldCarBean.removeAll(bean);
                        oldCarBean.addAll(bean.get(i).getGoods());
                    }
                }
            }

            //     shopCarBean = (ArrayList<ShopCarBean>) entity.getData();
            initEvents();
            if (shopCarBean == null
                    || shopCarBean.toString().equals("[]")) {
                setInvisible();
            } else {
                if (shopCarBean.size() <= 0) {
                    setInvisible();
                } else {
                    setVisible();
                }
            }
        } else if (entity.getEventType() == ShopPresenter.query_carfail) {
            setInvisible();
            MAlert.alert("购物车暂时没有东西");
        } else if (entity.getEventType() == ShopPresenter.deleteShop_success) {
            MAlert.alert(entity.getData() + "");
            carPresenter.gouWuChe(IsUtilUid.sId(), uid);
        } else if (entity.getEventType() == ShopPresenter.deleteShop_fail) {
            MAlert.alert(entity.getData());
        } else if (entity.getEventType() == ShopPresenter.updateShop_success) {
            try {
                Iterator<ShopCarBean.GoodsEntity> iterable = shopCarBean.get(groupPosition).getGoods().iterator();
                while (iterable.hasNext()) {
                    if (shopCarBean.get(groupPosition).getGoods()
                            .get(childPosition).getId().equals(id)) {
                        shopCarBean.get(groupPosition).getGoods()
                                .get(childPosition)
                                .setCount(currentCountTemp + "");
                        break;
                    }
                }
                mAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
            MAlert.alert(entity.getData() + "");
            calculate();
        } else if (entity.getEventType() == ShopPresenter.updateShop_fail) {
            MAlert.alert(entity.getData() + "");
        }
        try {
            closeProgressDialog();
            dialog.dismiss();
        } catch (Exception e) {
        }
    }

    /**
     * 删除Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(getActivity(), R.style.rel_dialog);
        View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_delete, null);
        dialog.setContentView(view);

        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        TextView user_title = (TextView) view.findViewById(R.id.user_title);
        TextView dialog_conext = (TextView) view.findViewById(R.id.dialog_conext);
        user_title.setText("删除账户");
        dialog_conext.setText("确定删除该账户？");

        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                showProgressDialog("删除中,请稍后", true);
                carPresenter.deleteShop(model);

            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }
}
